﻿using System;
using System.Net;
using System.Net.Sockets;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;

using System.Windows.Forms;

namespace IndustryFieldCommunication
{
    class Listener
    {
        public Listener(Action<Socket> OnAcceptOne)
        {
            AcceptOne += OnAcceptOne;
        }

        public async void StartListen(IPAddress ipAddress, int port)
        {
            ListenSocket = new Socket(ipAddress.AddressFamily,
                SocketType.Stream, ProtocolType.Tcp);
            IPEndPoint listenerEndPoint = new IPEndPoint(ipAddress, port);
            bStop = false;
            try
            {
                ListenSocket.Bind(listenerEndPoint);
                ListenSocket.Listen(100);
                while (!bStop)
                {
                    var task = ListenSocket.AcceptAsync();
                    if (!bStop)
                    {
                        var client = await task;
                        Clients.Add(client);
                        AcceptOne?.Invoke(client);
                    }
                }
            }
            catch (SocketException e)
            {
                if (e.SocketErrorCode == SocketError.OperationAborted)
                {
                    if (!bStop)
                        MessageBox.Show(e.ToString(), "在StartListen", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                }
                else
                    MessageBox.Show(e.ToString(), "在StartListen", MessageBoxButtons.OK, MessageBoxIcon.Warning);
            }
        }

        public void StopListen()
        {
            try
            {   
                bStop = true;
                ListenSocket.Close();//强制关闭
            }
            catch(Exception e)
            {
                MessageBox.Show(e.ToString(), "在StopListen", MessageBoxButtons.OK, MessageBoxIcon.Warning);
            }
        }

        public bool IsStoped()
        {
            return bStop;
        }

        bool bStop = true;
        Action<Socket> AcceptOne;
        Socket ListenSocket;
        List<Socket> Clients = new List<Socket>();
    }
}
